<template>
  <div class="third-comp">
    <div class="left">
      <el-card shadow="hover">
        <template #header>
          <h2>关键词搜索</h2>
        </template>
        <template #default>
          <div class="main">
            <!-- 1.图表区 -->
            <div class="charts">
              <div class="left-chart">
                <div class="title">搜索用户量</div>
                <div class="number">{{ userNum }}</div>
                <v-chart :option="userOption"></v-chart>
              </div>
              <div class="right-chart">
                <div class="title">搜索量</div>
                <div class="number">{{ searchNum }}</div>
                <v-chart :option="searchOption"></v-chart>
              </div>
            </div>
            <!-- 2.表格区 -->
            <div class="table">
              <!-- 表格 -->
              <el-table :data="PageData">
                <el-table-column label="排名" prop="rank"></el-table-column>
                <el-table-column
                  label="关键词"
                  prop="keyWord"
                ></el-table-column>
                <el-table-column
                  label="总搜索量"
                  prop="totalSearch"
                ></el-table-column>
                <el-table-column
                  label="搜索用户数"
                  prop="totalUser"
                ></el-table-column>
              </el-table>
              <!-- 分页器 -->
              <!-- $event 代表事件传递的参数。
              若分页组件触发时携带新页码则$event值更新。-->
              <el-pagination
                background
                layout="prev,pager,next"
                :total="tableData.length"
                :page-size="6"
                @current-change="page = $event"
              ></el-pagination>
            </div>
          </div>
        </template>
      </el-card>
    </div>
    <div class="right">
      <el-card shadow="hover">
        <template #header>
          <h2>热门搜索</h2>
          <el-radio-group v-model="type" @change="handleChange">
            <el-radio-button label="品类" value="category"></el-radio-button>
            <el-radio-button label="商品" value="product"></el-radio-button>
          </el-radio-group>
        </template>
        <template #default>
          <v-chart :option="categoryOption"></v-chart>
        </template>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getKeywordsData, getCategoryData } from '@/api'

const type = ref('category') // 热门搜索类型
const tableData = ref([])
const categoryData = ref([])
const categoryOption = ref({}) // 分类搜索图表配置
const userOption = ref({})
const searchOption = ref({})
const page = ref(1) //当前选中的页码
const PageData = computed(() => {
  // 计算当前页数据的起始索引（基于0开始）
  const start = (page.value - 1) * 6
  // 计算当前页数据的结束索引（不包含）
  const end = start + 6
  // 返回新数组，包含索引 [start, end) 的元素
  return tableData.value.slice(start, end)
})

const userNum = computed(() => {
  // acc: 累加器，保存当前累加的结果
  // cur: 当前遍历到的数组元素（对象）
  // 初始值为 0
  return tableData.value.reduce((acc, cur) => acc + cur.totalUser, 0)
})
const searchNum = computed(() => {
  return tableData.value.reduce((acc, cur) => acc + cur.totalSearch, 0)
})

const renderLineChart = (chartOption, data) => {
  chartOption.value = {
    xAxis: {
      type: 'category',
      show: false,
      boundaryGap: false,
    },
    yAxis: {
      type: 'value',
      show: false,
    },
    grid: {
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
    },
    series: {
      type: 'line',
      data: data,
      areaStyle: {
        color: 'skyblue',
      },
      itemStyle: {
        opacity: 0,
      },
      smooth: true,
    },
  }
}

const renderPieChart = (data) => {
  const _data=data.map((item)=>{
    return{
      name:`${item.title}|${item.value}`,
      title:item.title,
      value:item.value
    }
  })
  const total = data.reduce((acc, cur) => acc + cur.value, 0)
  categoryOption.value = {
    title: [
      {
        text: '品类分布',
        textStyle: {
          fontSize: 14,
          color: '#666',
        },
      },
      {
        text: '累计订单量',
        subtext: total,// 副标题文本（通常为动态数据）
        textAlign: 'center',
        x: '40%',
        y: '45%',
        textStyle: {
          fontSize: 14,
          color: '#999',
        },
        subtextStyle: {
          fontSize: 28,
          color: '#333',
        },
      },
    ],
    // 图例
    legend:{
      // legend要求series的data数组中对象必须有name属性
      orient: 'vertical',// 图例垂直排列
      left: '80%',
      top: 'top',
      textStyle: {
        color: '#888',
      },
    },
    // 弹框
    tooltip:{
      //params:ECharts自动传递的参数对象，包含当前数据点的详细信息。
      formatter(params){
        console.log(params)
        return`
        ${params.seriesName}<br>
        ${params.marker}${params.data.title}<br>
        ${params.marker} 销售额：${params.data.value}`
      }
    },
    series: {
      type: 'pie',
      name: '品类分布',
      data: _data,
      radius: ['45%', '60%'], // 设置饼图内外半径（百分比）
      center:['40%','50%'],//中心坐标点
      label:{
        position:'outside',
        formatter(params){
          return params.data.title
        }
      },
      itemStyle: {
        borderWidth: 8,
        borderColor: '#fff',
      },
    },
  }
}

const handleChange=()=>{
  if (type.value === 'category') {
    renderPieChart(categoryData.value.data1)
  } else if (type.value == 'product') {
    renderPieChart(categoryData.value.data2)
  }
}

onMounted(async () => {
  tableData.value = await getKeywordsData()
  categoryData.value = await getCategoryData()
  // console.log(tableData.value)
  // 从小到大排序
  const userData = tableData.value
    .map((item) => item.totalUser)
    .slice(0, 10)
    .sort((a, b) => a - b)
  const searchData = tableData.value
    .map((item) => item.totalSearch)
    .slice(0, 10)
    .sort((a, b) => a - b)
  renderLineChart(userOption, userData)
  renderLineChart(searchOption, searchData)

  renderPieChart(categoryData.value.data1)
})
</script>

<style lang="scss" scoped>
.third-comp {
  margin-top: 20px;
  display: flex;
  gap: 20px;
  .left {
    flex: 1;
    h2 {
      font-weight: 600;
    }
    .main {
      padding: 20px;
      .charts {
        display: flex;
        gap: 20px;
        .left-chart,
        .right-chart {
          flex: 1;
          .title {
            font-size: 14px;
            color: #727171;
          }
          .number {
            margin-top: 10px;
            font-size: 20px;
            font-weight: 600;
          }
          // v-chart设置的默认样式
          .echarts {
            height: 50px;
          }
        }
      }
      .table {
        .el-pagination {
          margin-top: 16px;
          display: flex;
          justify-content: end;
        }
      }
    }
  }
  .right {
    flex: 1;
    :deep(.el-card__header) {
      position: relative;
      h2 {
        font-weight: 600;
      }
      .el-radio-group {
        position: absolute;
        top: 10px;
        right: 20px;
      }
    }
    :deep(.el-card__body) {
      height: 502px;
      box-sizing: border-box;
    }
  }
}
</style>
